//
//  MGLRequsetFactory.m
//  CPManage
//
//  Created by lvho on 2017/4/26.
//  Copyright © 2017年 com.jiaoshou.chen. All rights reserved.
//

#import "MSLRequsetFactory.h"
#import "MSCommonParamsGenerator.h"
#import "AFURLRequestSerialization.h"
#import "MSNetworkHelper.h"

@interface MSLRequsetFactory ()

@property (strong, nonatomic) AFHTTPRequestSerializer *requestSerialize;

@property (strong, nonatomic) NSArray *hosts;

@end

@implementation MSLRequsetFactory


#pragma mark - Interface

- (void)switchService {
    if (_hosts.count>1) {
        
    }
}

- (NSMutableURLRequest *)generateRequestWithUrlPath:(NSString *)urlPath
                                              hosts:(NSArray <NSString *>*)hosts
                                           useHttps:(BOOL)useHttps
                                             method:(NSString *)method
                                             params:(NSDictionary *)params
                                             header:(NSDictionary *)header{
    _hosts = hosts;
    NSString *urlString = [self urlStringWithPath:urlPath useHttps:useHttps];
    NSMutableURLRequest *request = [self.requestSerialize requestWithMethod:method URLString:urlString parameters:params error:nil];
    request.timeoutInterval = 10;
    [self setCommonRequestHeaderForRequest:request];
    [header enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) {
        [request setValue:value forHTTPHeaderField:key];
    }];
    return request;
}


#pragma mark - Utils

- (NSString *)urlStringWithPath:(NSString *)path useHttps:(BOOL)useHttps {
    //如果是完整地址
    if ([path hasPrefix:@"http"]) {
        return path;
    } else {
        NSString *baseUrlString = _hosts[0];
//        if (useHttps && baseUrlString.length > 4) {
//            NSMutableString *mString = [NSMutableString stringWithString:baseUrlString];
//            [mString insertString:@"s" atIndex:4];
//            baseUrlString = [mString copy];
//        }
        return [NSString stringWithFormat:@"%@%@", baseUrlString, path];
    }
}

- (void)setCookies {
    
}

- (NSMutableURLRequest *)setCommonRequestHeaderForRequest:(NSMutableURLRequest *)request {
    //在这里设置通用的请求头
    [[MSCommonParamsGenerator commonParams] enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if (![MSNetworkHelper isNull:obj] && ![MSNetworkHelper isNull:key]) {
            [request setValue:obj
           forHTTPHeaderField:key];
        }
    }];
    return  request;
}

#pragma mark - Getter

- (AFHTTPRequestSerializer *)requestSerialize {
    if (!_requestSerialize) {
        _requestSerialize = [AFHTTPRequestSerializer serializer];
    }
    return _requestSerialize;
}
@end
